package com.changgou.goods.service.Impl;

import com.changgou.goods.dao.GoodsMapper;
import com.changgou.goods.service.GoodsService;
import com.changgou.pojo.Brand;
import com.changgou.pojo.Goods;
import entity.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Result<Goods> findAll() {
        return (Result<Goods>) goodsMapper.selectAll();
    }

    @Override
    public Goods findById(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    public Result add(Goods goods) {
        goodsMapper.insert(goods);
        return null;
    }

    public void updateByPrimaryKey(Goods goods) {
        goodsMapper.updateByPrimaryKey(goods);
    }

    public Result delete(Integer id) {
        goodsMapper.deleteByPrimaryKey(id);
        return null;
    }

    /**
     * 条件查询
     * @param goods
     * @return
     */
    @Override
    public List<Goods> findList(Goods goods){
        //构建查询条件
        Example example = createExample(goods);
        //根据构建的条件查询数据
        return goodsMapper.selectByExample(example);
    }


    /**
     * 构建查询对象
     * @param goods
     * @return
     */
    public Example createExample(Goods goods){
        Example example=new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if(goods!=null){
            // 产品名称
            if(!StringUtils.isEmpty(goods.getName())){
                criteria.andLike("name","%"+goods.getName()+"%");
            }
            // 产品图片地址
            if(!StringUtils.isEmpty(goods.getImage())){
                criteria.andLike("image","%"+goods.getImage()+"%");
            }
            // 品牌外键
            if(!StringUtils.isEmpty(goods.getBrand_id())){
                criteria.andLike("brand_id",goods.getBrand_id());
            }
            // 品牌id
            if(!StringUtils.isEmpty(goods.getId())){
                criteria.andEqualTo("id",goods.getId());
            }
            // 产品介绍
            if(!StringUtils.isEmpty(String.valueOf(goods.getDesc()))){
                criteria.andEqualTo("seq",goods.getDesc());
            }
            // 产品价格
            if(!StringUtils.isEmpty(String.valueOf(goods.getPrice()))){
                criteria.andEqualTo("seq",goods.getPrice());
            }
        }
        return example;
    }
}
